import axios from "axios";
import { getUserInfo } from "./storage";
import { checkCountryByTimeZone, checkLanguageByTimeZone, checkOSType, toSafeString } from "./utils";
import { BaseUrl } from "./apiUrl";
import DeviceID from "./deviceId";

// 1. 创建新的 axios 实例
const http = axios.create({
    baseURL: BaseUrl,
    timeout: 50000,
    withCredentials: true,
    responseType: 'json',
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    }
})

// 2. 设置请求拦截器和响应拦截器
http.interceptors.request.use(config => {
    console.log(config.data)
    return config
})

// 3. 设置请求响应拦截器
http.interceptors.response.use(response => {
    console.log(response)

    // 保存token
    let gHeaders = response.headers || {};
    let gToken = gHeaders.authorization || "";
    // console.log(gToken);

    // 保存token
    let data = { ...response.data }
    data.token = gToken;

    return data
}, err => {
    return Promise.reject(err)
})

// 4. 导出该 axios 实例
export default http

// 导出基本头
export const baseHeaders = () => {

    const userInfo = getUserInfo();
    const token = toSafeString(userInfo.token);

    const pHeaders = {
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Authorization': token
        }
    }

    return pHeaders;
};

//导出基本参数
export const baseParams = function initParams() {
    // //缓存用户信息
    // const userInfo = getUserInfo()
    // //缓存token
    // const token = toSafeString(userInfo.token)
    // //缓存userId
    // const userId = toSafeString(userInfo.userId)

    //设备id
    const deviceId = DeviceID.getVisitorId()

    //组装aduid
    // let aduid = DeviceID.getAduid()

    let params = {}
    // params.token = token
    // params.userId = userId
    // params.clientType = checkOSType()
    params.androidId = deviceId
    params.advertId = deviceId
    params.app = "cmcwallet"
    params.channel = "H5"
    // params.channelCode = "cmcwallet"
    // params.subChannelCode = "cmcwallet"
    params.appVersion = "6000"
    params.clientType = checkOSType()
    params.country = checkCountryByTimeZone()
    params.language = checkLanguageByTimeZone()
    params.reInstall = false
    return params
}
